#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <src/get_temperature/get_temperature.h>

// 获取温度节点
#define MLX90614_OBJ_TEMP_DEV "/sys/devices/platform/soc/fe804000.i2c/i2c-1/1-005a/iio:device0/in_temp_object_raw"
#define MLX90614_AMBIENT_TEMP_DEV "/sys/devices/platform/soc/fe804000.i2c/i2c-1/1-005a/iio:device0/in_temp_ambient_raw"

static char temp_buf[20];

int get_temperature(double *temp_object_p, double *temp_ambient_p)
{
    int ret = 0;
    int fd_obj, fd_ambient;
    int temp_raw;
    double temp;
    fd_obj = open(MLX90614_OBJ_TEMP_DEV, O_RDONLY);
    if(fd_obj < 0)
    {
//        perror("open MLX90614_TEMP_DEV failed : ");
        return fd_obj;
    }
    fd_ambient = open(MLX90614_AMBIENT_TEMP_DEV, O_RDONLY);
    if(fd_ambient < 0)
    {
//        perror("open MLX90614_TEMP_DEV failed : ");
        close(fd_obj);
        return fd_obj;
    }
    ret = read(fd_obj, temp_buf, 20);
    if(ret < 0)
    {
//        perror("get temperature failed : ");
        close(fd_obj);
        close(fd_ambient);
        return ret;
    }
//    printf("temperature : %s\n", temp_buf);
    temp_raw = atoi(temp_buf);
    temp = temp_raw * 0.02 -273.15;
    if(temp_object_p)
    {
        *temp_object_p = temp;
    }

    // get ambient tempterature
    ret = read(fd_ambient, temp_buf, 20);
    if(ret < 0)
    {
        close(fd_obj);
        close(fd_ambient);
//        perror("get temperature failed : ");
        return ret;
    }
//    printf("ambient temperature : %s\n", temp_buf);
    temp_raw = atoi(temp_buf);
    temp = temp_raw * 0.02 -273.15;
    if(temp_ambient_p)
    {
        *temp_ambient_p = temp;
    }
    close(fd_obj);
    close(fd_ambient);
    return 0;
}
